#include "ChatServer.hpp"

void Useage_Client(char *ch[])
{
    std::cout << "Useage" << ch[0] << " ip port" << std::endl;
}


struct Data
{
    Data(int sockfd, Inet_Addr addr)
        : _sockfd(sockfd),  _addr(addr)
    {
    }

    int _sockfd;
    Inet_Addr _addr;
};


void *Read(void *args)
{
    struct Data *_ptr = static_cast<struct Data *>(args);
    char buffer[1024];


    while (1)
    {
        socklen_t len = _ptr->_addr.Size();
        int n = recvfrom(_ptr->_sockfd,buffer,sizeof(buffer),0,_ptr->_addr.Addr(),&len);
        if(n > 0)
        {
            buffer[n] = 0;
            std::cout << buffer << std::endl;
        }
    }

    return nullptr;
}


void * Write(void *args)
{
    struct Data *_ptr = static_cast<struct Data *>(args);
    std::string _message;

    while (std::getline(std::cin,_message))
    {
        socklen_t len = _ptr->_addr.Size();
        int n = sendto(_ptr->_sockfd,_message.c_str(),_message.size(),0,_ptr->_addr.Addr(),len);
    }


    return nullptr;
}



int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Useage_Client(argv);
        exit(1);
    }

    int _socketfd = socket(AF_INET, SOCK_DGRAM, 0);
    std::string ip = argv[1];
    std::string port = argv[2];

    struct sockaddr_in _src;
    memset(&_src, 0, sizeof(_src));
    _src.sin_family = AF_INET;
    _src.sin_addr.s_addr = inet_addr(ip.c_str());
    // _src.sin_port = std::stoi(port);
    _src.sin_port = htons(std::stoi(port)); // 转换成网络序列

    // while (1)
    // {
    //     std::string _line;
    //     std::getline(std::cin, _line);

    //     socklen_t len = sizeof(_src);
    //     char buffer[1024] = {0};
    //     ssize_t n = sendto(_socketfd, _line.c_str(), _line.size(), 0, (struct sockaddr *)&_src, len);

    //     // ssize_t m = recvfrom(_socketfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&_src, &len);
    //     // if (m > 0)
    //     // {
    //     //     buffer[m] = 0;
    //     //     std::cout << buffer << std::endl;
    //     // }
    // }

    pthread_t tid_1, tid_2;

    Data d1(_socketfd, _src);

    pthread_create(&tid_1, nullptr, Read, (void *)&d1);
    pthread_create(&tid_2, nullptr, Write, (void *)&d1);

    pthread_join(tid_1,nullptr);
    pthread_join(tid_2,nullptr);

    return 0;
}